package servlet.rool;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import service.RoleService;
import service.impl.RoleServiceImpl;
import util.JsonDateValueProcessor;
import util.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 角色分页的servlet
 */
@WebServlet(value = "/RolePageServlet")
public class RolePageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置返回的格式
        response.setContentType("text/json;charset=UTF-8");
        PageBean pb=new PageBean();
        String pageIndex=request.getParameter("page");//每页显示记录数
        if(null==pageIndex){
            pb.setPageIndex(1);
        }else {
            pb.setPageIndex(Integer.parseInt(pageIndex));
        }
        String pageSize=request.getParameter("limit");
        if(null==pageSize){
            pb.setPageSize(2);
        }else {
            pb.setPageSize(Integer.parseInt(pageSize));
        }

        RoleService rs=new RoleServiceImpl();

        String name=request.getParameter("name");
        pb=rs.rolePageList(pb,name);
        //创建json对象
        JSONObject json=new JSONObject();
        json.put("code",0);//状态码
        json.put("msg","");//附带消息
        json.put("count",pb.getTotalCount());//总记录数，用于layui计算页数
        //把list转换成json数组
        JsonConfig config=new JsonConfig();
        config.registerJsonValueProcessor(java.util.Date.class,new JsonDateValueProcessor());
        JSONArray array= JSONArray.fromObject(pb.getList(),config);
        json.put("data",array);
        PrintWriter out=response.getWriter();
        out.print(json);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doGet(request, response);
    }
}
